from .base import BaseHandler
from tornado.websocket import WebSocketHandler
import sys
import time
from tornado import gen
import tornado.web
sys.path.append("..")
from db import sess,Person,AlchemyEncoder,Cate,Role,Role_Node,Node
import json
import requests
import os
import datetime
import pymongo
from bson import json_util as jsonb
mongo_client = pymongo.MongoClient(host='localhost', port=27017)


#展示数据
class AllHandler(BaseHandler):
    def get(self):
        self.render('../templates/all.html')

#插入数据
class InsertHandler(BaseHandler):
    def get(self):
        self.render('../templates/insert.html')

    def post(self):
        db = mongo_client.interview
        table = db.interview

        result = 'ok'

        title = self.get_argument('title',None)
        desc = self.get_argument('desc',None)
        com = self.get_argument('com',None)


        res = table.find({"title":title}).count()
        print(res)

        if title == None or desc == None or title == '' or desc == '':
            self.write(json.dumps({'result':'缺少参数:title/desc'},ensure_ascii=False))
            self.finish()
            return False

        if(res > 0):
            result = '重复数据'
            self.write(json.dumps({'result':result},ensure_ascii=False))
            self.finish()
            return False

    
        
        
        try:
            table.insert({'title':title,'desc':desc,'com':com})
        except Exception as e:
            print(str(e))
            result = '服务异常，请联系管理员'
        
        self.write(json.dumps({'result':result},ensure_ascii=False))
        self.finish()


#查看数据
class FindHandler(BaseHandler):
    def get(self):
        db = mongo_client.interview
        table = db.interview

        mylist = []
       
        word = self.get_argument('word',None)


        if word == None:
            res = table.find({})
        else:
            
            res = table.find({"title":{"$regex":word,"$options":"i"}}).hint('title_text')

        for result in res:
            mylist.append(result)
        
        self.write(jsonb.dumps({'result':mylist},ensure_ascii=False))



#查看公司
class ComHandler(BaseHandler):
    def get(self):
        db = mongo_client.interview
        table = db.interview

        mylist = []
       
        word = self.get_argument('word',None)


        pipeline = [{'$group': {'_id': "$com", 'count': {'$sum': 1}}},]
        res = table.aggregate(pipeline)

        for result in res:
            if result['_id'] != '':
                if word == None:
                    mylist.append(result)
                else:
                    if result['_id'].find(word) != -1:
                        mylist.append(result)
        
        self.write(jsonb.dumps({'result':mylist},ensure_ascii=False))


#查看数据
class FindComHandler(BaseHandler):
    def get(self):
        db = mongo_client.interview
        table = db.interview

        mylist = []
       
        word = self.get_argument('word',None)


        if word == None:
            res = table.find({})
        else:
            
            res = table.find({"com":word}).hint('com_text')

        for result in res:
            mylist.append(result)
        
        self.write(jsonb.dumps({'result':mylist},ensure_ascii=False))



#随机取一条数据
class ChromeHandler(BaseHandler):
    def get(self):
        db = mongo_client.interview
        table = db.interview

        mylist = []


        pipeline = [{ '$sample': { 'size': 2 } },{'$match':{"com":""}}]
        res = table.aggregate(pipeline)

        for result in res:
            print(result)
            mylist.append(result)
            break
        
        self.write(jsonb.dumps({'result':mylist},ensure_ascii=False))